package com.aircms.util;

import com.aircms.common.Common;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class JwtUtil {
    private static int expiresIn= 60*60*24;       // 有效期(秒)
    private static String signature="aircms&JwtSecret&%";  // 签名
    private static String token_type="Bearer";
    private static String err;

    private static final Logger logger=LoggerFactory.getLogger(JwtUtil.class);


    public static int getExpiresIn() {
        return expiresIn;
    }

    public static String getErr() {
        return err;
    }

    public static void setExpiresIn(int expiresIn) {
        JwtUtil.expiresIn = expiresIn;
    }
    public static String getSignature() {
        return signature;
    }

    /**
     * 生成token
     * @param data
     * @param id
     * @return
     */
    public static String createJwt(Map data,String id){
        String jwt=Jwts.builder()
                .setClaims(data)
                .setId(id)
                .setSubject(UUID.randomUUID().toString())
                .setExpiration(new Date(System.currentTimeMillis() + 1000*expiresIn))
                .signWith(SignatureAlgorithm.HS512, signature)
                .compact();
        return jwt;
    }


    /**
     * 解析token，并返回相应的key值
     * @param string
     * @param key
     * @return
     */
    public static  String parserJwt(String string,String key) {
        try{
            Claims jwtBody=Jwts.parser().setSigningKey(signature).parseClaimsJws(string.replace(token_type, "")).getBody();

            if(!jwtBody.getId().equals(MD5Util.MD5Encode(Common.getIp()+Common.getUserAgent()))){ // 判断ip是否是同一台电脑,且同一浏览器
                logger.error(Common.getIp()+": 此ip正在进行非法操作");
                return "false";
            }
            return jwtBody.get(key).toString();
        }catch (SignatureException|ExpiredJwtException e){
            logger.error(String.valueOf(e));
            err= String.valueOf(e);
            return "false";
        }
    }
}
